package tech.aistar.interceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.aistar.pojo.User;
import tech.aistar.utils.JwtUtils;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("================");
        String token = request.getHeader("Authorization");
        if(token == null || token.isEmpty()){
            //TODO...
            System.out.println("no token");
        }else{
            Claims claims = JwtUtils.verifyToken(token);
            if(claims != null){
                Integer userId = claims.get("id",Integer.class);
                System.out.println("userId:"+userId);
                String username = claims.get("username",String.class);
                System.out.println("username:"+username);
                User user = new User();
                user.setUsername(username);
                user.setId(userId);
                System.out.println("拦截器:"+user);
                request.setAttribute("loginUser",user);
                return true;
            }
        }
        return false;
    }
}
